from PIL import Image
import os
import shutil

def compress_image(image_path, max_size=4*1024*1024):
    # 读取图片
    with Image.open(image_path) as img:
        # 获取原始图片的元数据
        metadata = img.info
        # 压缩图片至最大大小限制
        img.save(image_path, optimize=True, quality=85)
        # 重新读取图片以获取新的大小
        with Image.open(image_path) as img_compressed:
            # 检查压缩后的图片大小
            if img_compressed.size[0] * img_compressed.size[1] * 3 / 2 <= max_size:
                return image_path, metadata
            else:
                # 如果压缩后大小仍然超过限制，则再次压缩
                img.save(image_path, optimize=True, quality=75)
                return image_path, metadata

def compress_images(root_dir):
    for subdir, dirs, files in os.walk(root_dir):
        for file in files:
            if file.lower().endswith(('.png', '.jpg', '.jpeg')):
                file_path = os.path.join(subdir, file)
                compressed_path, metadata = compress_image(file_path)
                if compressed_path and metadata:
                    print(f'压缩了文件：{file_path}，新文件：{compressed_path}，元数据：{metadata}')
                    # 删除原始文件，保留压缩后的文件
                    os.remove(file_path)
                    shutil.move(compressed_path, file_path)

# 设置需要遍历的文件夹
root_dir = 'pic'
compress_images(root_dir)
